from rest_framework import serializers
import markdown
import logging
from .models import Article, Category,Tag
from django.urls import reverse
from account.models import CustomUser
from django.utils import timezone
from datetime import datetime, timedelta
# 设置日志记录器
logger = logging.getLogger(__name__)


class ArticleSerializer(serializers.ModelSerializer):
    # Markdown 转换字段
    html_content = serializers.SerializerMethodField()
    # 作者头像URL
    author_avatar_url = serializers.SerializerMethodField()
    # 封面图绝对地址
    cover_url = serializers.SerializerMethodField()
    # 标签列表
    # tags = serializers.PrimaryKeyRelatedField(many=True, queryset=Tag.objects.all())
    # 作者详情链接
    author_url = serializers.SerializerMethodField()
    # 作者名字
    author_name = serializers.SerializerMethodField()
    # 分类
    category_name = serializers.SerializerMethodField()
    # 格式化的创建日期
    formatted_created_time = serializers.SerializerMethodField()

    class Meta:
        model = Article
        fields = '__all__'
        read_only_fields = ['views', 'likes', 'comments', 'collects']
        extra_kwargs = {
            'author': {'read_only': True}
        }

    def get_html_content(self, obj):
        """Markdown 转 HTML 并添加扩展支持"""
        try:
            return markdown.markdown(
                obj.content,
                extensions=[
                    'markdown.extensions.extra',  # 包含表格等多种扩展
                    'markdown.extensions.codehilite',  # 代码高亮
                    'markdown.extensions.toc',  # 目录生成
                    'markdown.extensions.nl2br',  # 换行转换
                    'markdown.extensions.sane_lists',  # 更智能的列表处理
                    'markdown.extensions.smarty',  # 智能标点符号
                    'markdown.extensions.wikilinks',  # Wiki链接支持
                    'markdown.extensions.tables',  # 表格支持(已包含在extra中，这里再次指定以确保启用)
                    'markdown.extensions.fenced_code',  # 围栏代码块(已包含在extra中)
                ],
                extension_configs={
                    'markdown.extensions.codehilite': {
                        'linenums': True,  # 显示行号
                        'guess_lang': True,  # 自动检测语言
                    },
                    'markdown.extensions.toc': {
                        'title': '目录',  # 目录标题
                        'toc_depth': 3,  # 目录深度，1-6
                        'permalink': True,  # 为标题添加永久链接
                    }
                }
            )
        except Exception as e:
            # 记录错误日志
            logger.error(f"Markdown 转换失败: {str(e)}")
            return obj.content  # 返回原始内容

    def get_cover_url(self, obj):
        """生成封面图完整 URL"""
        if obj.cover:
            request = self.context.get('request')
            return request.build_absolute_uri(obj.cover.url) if request else obj.cover.url
        return None

    def get_author_url(self, obj):
        """生成作者详情 API 地址"""
        request = self.context.get('request')
        # 使用Djoser提供的用户API路径
        if request:
            return request.build_absolute_uri(f'/api/users/{obj.author.id}/')
        return f'/api/users/{obj.author.id}/'

    def get_formatted_created_time(self, obj):
        """格式化创建时间"""
        now = timezone.now()
        created = obj.created_time
        
        # 计算时间差
        delta = now.date() - created.date()
        
        # 今天创建的
        if delta.days == 0:
            return "今天"
        # 昨天创建的
        elif delta.days == 1:
            return "昨天"
        # 7天内创建的
        elif delta.days < 7:
            return f"{delta.days}天前"
        # 超过7天的显示年月日
        else:
            return created.strftime("%Y-%m-%d")

    def get_author_name(self, obj):
        """获取作者名字"""
        return obj.author.username if obj.author else ""

    def get_category_name(self, obj):
        """获取分类名字"""
        return obj.category.name if obj.category else ""

    def get_author_avatar_url(self, obj):
        """获取作者头像的完整URL"""
        if obj.author and obj.author.avatar:
            request = self.context.get('request')
            return request.build_absolute_uri(obj.author.avatar.url) if request else obj.author.avatar.url
        return None

    def create(self, validated_data):
        """创建文章时自动设置当前用户为作者"""
        request = self.context.get('request')
        if request and request.user and request.user.is_authenticated:
            validated_data['author'] = request.user
        else:
            raise serializers.ValidationError({"author": "必须登录才能创建文章"})
        return super().create(validated_data)

    # 自定义方法处理字符串形式的标签ID
    # def validate_tags(self, value):
    #     if isinstance(value, list):
    #         # 尝试将字符串转换为整数
    #         try:
    #             tag_ids = [int(tag_id) if isinstance(tag_id, str) else tag_id for tag_id in value]
    #             return Tag.objects.filter(id__in=tag_ids)
    #         except (ValueError, TypeError):
    #             raise serializers.ValidationError("标签ID必须是整数")
    #     return value


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = '__all__'
# class TagsSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Tag
#         fields = '__all__'
